<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Exception;
use think\Request;
use think\Validate;
use TCPDF;

class Hotel extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 编辑
     */
    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            $postData['create_time'] = NOW_TIME;
            $postData['open_time'] = strtotime($postData['open_time']);
            $postData['decorate_time'] = strtotime($postData['decorate_time']);
            $updateCount = Db::name('hotel')->strict(false)->update($postData);
            if ($updateCount){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }

            $vo = Db::name('hotel')->where('id',$data['id'])->find();
            // 查询所有的酒店
            $this->view->assign('vo',$vo);
            return $this->view->fetch();
        }
    }

    /**
     * 获取酒店房型数量
     */
    public static function getRoomPrices($data)
    {
        $map = [];
        // 根据酒店id查找
        $room_hotel_number = Db::name('room_hotel_number')->where('hotel_id', $data['id'])->select();
        if (!$room_hotel_number || !$data['id']) {
            $price = 0;
            $map['room_name'] = '尚未有房型';
            $map['num'] = 0;
            return $map;
        }
        $priceStr = '';
        foreach ($room_hotel_number as $index => $item) {
            $type_name = Db::name('hotel_room_type')->where('id', $item['room_type_id'])->value('room_name');
            if ($type_name) {
//                $priceStr .= "{$type_name} -- {$item['number_of_rooms']},";
                $map[] = [
                    'room_name' => $type_name,
                    'num' => $item['number_of_rooms'],
                ];
            } else {
                $map[] = [
                    'room_name' => '房型已被删除',
                    'num' => $item['number_of_rooms'],
                ];
            }
        }
        return $map;
    }

    /**
     * 导出数据到excel
     */
    public function get_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['司机','路线','入住日期','入住天数','酒店名称','房型','费用','合计','状态','备注'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(100);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(100);break;
                case 'L':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(100);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }


        $map['id'] = ['in',$data['ids']];
        //查询要填充表格数据
        $lists = Db::name('driver_hotel_expense')
            ->where($map)
            ->order('id','desc')
            ->select();

        //字段转换
        foreach ($lists as $lk=>$lv) {
            //司机
            if(!empty($lv['driver_user_id'])){
                $realname = Db::name('admin_user')->where('id',$lv['driver_user_id'])->value('realname');
            }
            $list[$lk]['realname'] = empty($realname) ? '' : $realname;
            //路线
            if(!empty($lv['group_id'])){
                $route_id = Db::name('dispatch_traveler_group')->where('id',$lv['group_id'])->value('route_id');
                $title = Db::name('route')->where('id',$route_id)->value('title');
            }
            $list[$lk]['title'] = empty($title) ? '' : $title;
            //入住日期
            $list[$lk]['check_in_date'] = empty($lv['check_in_date']) ? '' : date('Y-m-d',$lv['check_in_date']);
            //入住天数
            $list[$lk]['days'] = empty($lv['days']) ? '' : $lv['days'];
            //酒店名称
            $list[$lk]['hotel_name'] = $lv['hotel_name'];
            $list[$lk]['room_type_name'] = $lv['room_type_name'];
//            if(!empty($lv['hotel_id'])){
//                $hotel_name = Db::name('hotel')->where('id',$lv['hotel_id'])->value('hotel_name');
//            }
//            $list[$lk]['hotel_name'] = empty($hotel_name) ? '' : $hotel_name;
//            //房型
//            if(!empty($lv['room_type_id'])){
//                $room_name = Db::name('hotel_room_type')->where('id',$lv['room_type_id'])->value('room_name');
//            }
//            $list[$lk]['room_name'] = empty($room_name) ? '' : $room_name;
            //费用
            $list[$lk]['unit_price'] = empty($lv['unit_price']) ? '' : $lv['unit_price'];
            //合计
            $list[$lk]['total_price'] = empty($lv['total_price']) ? '' : $lv['total_price'];
            //状态
            switch ($lv['status']){
                case '0':
                    $status = '结算驳回';break;
                case '1':
                    $status = '结算成功';break;
                case '2':
                    $status = '申请中';break;
            }
            $list[$lk]['status'] = empty($status) ? '' : $status;
            //备注
            $list[$lk]['remark'] = empty($lv['remark']) ? '' : $lv['remark'];
        }
        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店安排-司机陪房管理数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }

    /**
     * 首页
     */
    public function index()
    {
        $data = input();
        if ($data['hotel_name']){
            $map['hotel_name'] = ["like", "%{$data['hotel_name']}%"];
        }

        $ids = [];
        if ($data['room_type_id']){
            $room_type_id = Db::name('room_hotel_number')->where('room_type_id',$data['room_type_id'])->column('hotel_id');
            $ids = $room_type_id;
            $is_serach = true;
        }

        if ($data['hotel_location']){
            $map['hotel_location'] = ["like", "%{$data['hotel_location']}%"];
        }

        if ($data['hotel_type']){
            $map['hotel_type'] = ["like", "%{$data['hotel_type']}%"];
        }

        if ($data['hotel_manager']){
            $map['hotel_manager'] = ["like", "%{$data['hotel_manager']}%"];
        }

        if ($data['phone']){
            $map['phone'] = ["like", "%{$data['phone']}%"];
        }

        if($data['account']){
            $is_serach = true;
            $account = Db::name('hotel_account')->where("account","like","%{$data['account']}%")->column('hotel_id');
            if(!empty($ids)){
                $ids = array_intersect($ids,$account);
            }else{
                $ids = $account;
            }
        }

        if($data['account_name']){
            $is_serach = true;
            $account_name = Db::name('hotel_account')->where("account_name","like","%{$data['account_name']}%")->column('hotel_id');
            if(!empty($ids)){
                $ids = array_intersect($ids,$account_name);
            }else{
                $ids = $account_name;
            }
        }

        if($data['account_bank']){
            $is_serach = true;
            $account_bank = Db::name('hotel_account')->where("account_bank","like","%{$data['account_bank']}%")->column('hotel_id');
            if(!empty($ids)){
                $ids = array_intersect($ids,$account_bank);
            }else{
                $ids = $account_bank;
            }
        }

        if(!empty($ids)){
            $hotel_ids = '';
            foreach ($ids as $k => $v) {
                $hotel_ids .= $v.',';
            }
            $hotel_ids = rtrim($hotel_ids,',');
            $map['id'] = ['in', $hotel_ids];
        }else{
            if($is_serach && isset($is_serach)){
                $map['id'] = '';
            }
        }

//        if ($data['open_time']){
//            $start_time = "{$data['open_time']} 0:0:0"; //开始时间
//            $end_time = "{$data['open_time']} 23:59:59"; // 结束时间
//            $map['open_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
//        }
//
//        if ($data['decorate_time']){
//            $start_time = "{$data['decorate_time']} 0:0:0"; //开始时间
//            $end_time = "{$data['decorate_time']} 23:59:59"; // 结束时间
//            $map['decorate_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
//        }

        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0"; //开始时间
            $end_time = "{$data['create_time']} 23:59:59"; // 结束时间
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }

        if ($data['remark']){
            $map['remark'] = ["like", "%{$data['remark']}%"];
        }

        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }

        // 根据id查找
        $listRows = $this->request->param('numPerPage') ?20: Config::get("paginate.list_rows");
        $list = Db::name('hotel')
            ->where($map)
            ->order('id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];
        if ($listData){
            foreach ($listData as $index => $listDatum) {
                $listData[$index]['room_data'] = self::getRoomPrices($listDatum);
                $hotel_account = Db::name('hotel_account')->where('hotel_id',$listDatum['id'])->select();
                $account_names = [];
                $accounts = [];
                $account_banks = [];
                if(count($hotel_account)>0){
                    foreach ($hotel_account as $hk => $hv){
                        $account_names[$hk] = $hv['account_name'];
                        $accounts[$hk] = $hv['account'];
                        $account_banks[$hk] = $hv['account_bank'];
                    }
                }
                $listData[$index]['account_names'] = $account_names;
                $listData[$index]['accounts'] = $accounts;
                $listData[$index]['account_banks'] = $account_banks;
            }
        }

        $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
        $count = $list->total();
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('listData', $listData);
        $this->view->assign('searchCondition',$data);
        $this->view->assign('hotel_room_type',$hotel_room_type);
        return view('',compact('list','count'));
    }

    /**
     * 添加
     */
    public function add(Request $request)
    {
        $data = input();

        if ($request->isPost()){
            // 处理post提交数据
        }else{
            // 渲染模板
            return $this->view->fetch();
        }

        if ($this->request->isAjax()) {

            $room_names = [];
            $room_nums = [];
            $accoun_names = [];
            $accouns = [];
            $accoun_banks = [];
            //获取酒店房型数据以及获取酒店账号信息
            foreach ($data as $k => $v){
                $temp_name = substr($k,0,10);
                $temp_room_num = substr($k,0,9);
                $temp_accoun_name = substr($k,0,12);
                $temp_accoun = substr($k,0,11);
                $temp_accoun_bank = substr($k,0,12);

                if($temp_name == 'room_name_'){
                    //房型名称
                    if(!empty($v)){
                        $room_names[] = $v;
                    }else{
                        return ajax_return_error('房型名称不能为空');
                    }
                }
                if($temp_room_num == 'room_num_'){
                    //房型数量
                    if(is_numeric($v)){
                        $room_nums[] = $v;
                    }else{
                        return ajax_return_error('房型数量格式有误');
                    }
                }
                if($temp_accoun_name == 'accoun_name_'){
                    //账户名称
                    if(!empty($v)){
                        $accoun_names[] = $v;
                    }else{
                        return ajax_return_error('房型名称不能为空');
                    }
                }
                if($temp_accoun == 'accoun_val_'){
                    //账户
                    if(!empty($v)){
                        $accouns[] = $v;
                    }else{
                        return ajax_return_error('房型名称不能为空');
                    }
                }
                if($temp_accoun_bank == 'accoun_bank_'){
                    //账户开户行
                    if(!empty($v)){
                        $accoun_banks[] = $v;
                    }else{
                        return ajax_return_error('房型名称不能为空');
                    }
                }
            }

            //整合酒店基本信息
            $insert_data = [
                'hotel_name' => $data['hotel_name'],
                'hotel_location' => $data['hotel_location'],
                'hotel_manager' => $data['hotel_manager'],
                'phone' => $data['phone'],
                'create_time' => time(),
                'remark' => $data['remark'],
            ];

            // 验证数据
            $rule = [
                'hotel_name' => 'require',
                'hotel_location' => 'require',
//                'hotel_manager' => 'require',
//                'phone' => 'require|number|max:25',
                'phone' => 'number|max:25',
            ];
            $message = [
                'hotel_name.require' => '酒店名称不能为空',
                'hotel_location.require' => '酒店位置不能为空',
                'hotel_manager.require' => '酒店经理不能为空',
//                'phone.require' => '联系电话不能为空',
                'phone.max' => '联系电话不可超过25个字符',
                'phone.number' => '联系电话格式填写有误',
            ];
            $valdate = new Validate($rule, $message);
            $result = $valdate->check($insert_data);
            if (!$result){
                return ajax_return_adv_error($valdate->getError());
            }

            Db::startTrans();
            try{

                //插入酒店信息并获取ID
                $hid = Db::name('hotel')->strict(false)->insertGetId($insert_data);

                if($hid){
                    //插入房型数据
                    if(count($room_names)>0){
                        foreach ($room_names as $tk => $tv){
                            $room_type = [
                                'hotel_id' => $hid,
                                'room_type_id' => $tv,
                                'number_of_rooms' => $room_nums[$tk],
                                'create_time' => time(),
                            ];

                            $room_type_id[] = Db::name('room_hotel_number')->strict(false)->insertGetId($room_type);
                        }
                    }

                    //插入酒店账号数据
                    if(count($accoun_names)>0){
                        foreach ($accoun_names as $ak => $av){
                            $hotel_account = [
                                'hotel_id' => $hid,
                                'account_name' => $av,
                                'account' => $accouns[$ak],
                                'account_bank' => $accoun_banks[$ak],
                                'create_time' => time(),
                            ];

                            $hotel_account_ids[] = Db::name('hotel_account')->strict(false)->insertGetId($hotel_account);
                        }
                    }
                    Db::commit();
                    return ajax_return_adv('添加成功');
                }else{
                    Db::rollback();
                    return ajax_return_error('添加失败');
                }
            }catch (\Exception $e){
                Db::rollback();
                return ajax_return_error('添加失败','hotel_add_exception',$e->getMessage());
            }

        }else{
            return ajax_return_error("暂无数据");
        }
    }

    /**
     * 酒店账号信息
     */
    public function hotel_account_info(){
        $data = input();

        if ($data['account_name']){
            $map['account_name'] = ["like", "%{$data['account_name']}%"];
        }

        if ($data['account']){
            $map['account'] = ["like", "%{$data['account']}%"];
        }

        if ($data['account_bank']){
            $map['account_bank'] = ["like", "%{$data['account_bank']}%"];
        }

        if(empty($data['hotel_id'])){
            return ajax_return_adv_error('缺少参数');
        }

        $hotel_account = Db::name('hotel_account')
            ->where($map)
            ->where('hotel_id',$data['hotel_id'])
            ->select();

        if(count($hotel_account)>0){
            $count = count($hotel_account);
        }else{
            $count = 0;
        }

        $hotel_info = Db::name('hotel')->where('id',$data['hotel_id'])->find();
        $this->view->assign('hotel_id',$hotel_info['id']);
        $this->view->assign('hotel_name',$hotel_info['hotel_name']);
        $this->view->assign('count',$count);
        $this->view->assign('list',$hotel_account);
        return $this->view->fetch();
    }

    /**
     * 添加酒店账号信息
     */
    public function add_hotel_account()
    {
        $data = input();

        $rule = [
            'hotel_id'=>'require',
            'account_name'=>'require',
            'account'=>'require',
            'account_bank'=>'require',
        ];
        $message = [
            'hotel_id.require' => '参数错误',
            'account_name.require' => '账号名称不能为空',
            'account.require' => '账号不能为空',
            'account_bank.require' => '账号开户行不能为空',
        ];
        $validate = new Validate($rule,$message);
        $result = $validate->check($data);
        if (!$result){
            return ajax_return_error($validate->getError());
        }

        $hotel_account = [
            'hotel_id' => $data['hotel_id'],
            'account_name' => $data['account_name'],
            'account' => $data['account'],
            'account_bank' => $data['account_bank'],
            'create_time' => time(),
        ];

        $ck = Db::name('hotel_account')->where('hotel_id',$data['hotel_id'])->where('account',$data['account'])->find();
        if($ck){
            return ajax_return_error('已存在该账号信息');
        }

        $res = Db::name('hotel_account')->strict(false)->insertGetId($hotel_account);

        if($res){
            return ajax_return_adv('添加成功');
        }else{
            return ajax_return_error('添加失败');
        }
    }

    /**
     * 编辑酒店账号信息
     */
    public function edit_hotel_account()
    {
        $data = input();

        $rule = [
            'id'=>'require',
            'account_name'=>'require',
            'account'=>'require',
            'account_bank'=>'require',
        ];
        $message = [
            'id.require' => '参数id错误',
            'account_name.require' => '账号名称不能为空',
            'account.require' => '账号不能为空',
            'account_bank.require' => '账号开户行不能为空',
        ];
        $validate = new Validate($rule,$message);
        $result = $validate->check($data);
        if (!$result){
            return ajax_return_error($validate->getError());
        }

        $ck = Db::name('hotel_account')->where('account',$data['account'])->find();
        if($ck && $ck['id']!=$data['id']){
            return ajax_return_error('账号已存在');
        }

        $hotel_account = [
            'account_name' => $data['account_name'],
            'account' => $data['account'],
            'account_bank' => $data['account_bank'],
        ];

        $res = Db::name('hotel_account')->strict(false)->where('id',$data['id'])->update($hotel_account);

        if($res){
            return ajax_return_adv('更新成功');
        }else{
            return ajax_return_error('更新失败');
        }
    }

    /**
     * 删除酒店账号信息
     */
    public function del_hotel_account()
    {
        $data = input();

        $rule = [
            'id'=>'require',
        ];
        $message = [
            'id.require' => '参数id错误',
        ];
        $validate = new Validate($rule,$message);
        $result = $validate->check($data);
        if (!$result){
            return ajax_return_error($validate->getError());
        }

        $res = Db::name('hotel_account')->where('id',$data['id'])->delete();

        if($res){
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_error('删除失败');
        }
    }

    /**
     * 司陪房费用
     */
    public function driver_hotel_expense(Request $request)
    {
        $data = input();

        $map = [];
        if($data['route_title']){
            $title['title'] = ['like','%'.$data['route_title'].'%'];
            $route_id = Db::name('route')->where($title)->column('id');
            $group_id = [];
            if(count($route_id) > 0){
                foreach ($route_id as $kr => $vr){
                    $group_id[] = Db::name('dispatch_traveler_group')->where('route_id',$vr)->value('id');
                }

            }
            $map['group_id'] = ['in',$group_id];
        }
        if($data['driver_name']){
            $driver_name['realname'] = ['like','%'.$data['driver_name'].'%'];
            $driver_ids = Db::name('admin_user')->where($driver_name)->column('id');
            $map['driver_user_id'] = ['in',$driver_ids];
        }
        if($data['hotel_name']){
            $hotel_name['hotel_name'] = ['like','%'.$data['hotel_name'].'%'];
            $hotel_ids = Db::name('hotel')->where($hotel_name)->column('id');
            $map['hotel_id'] = ['in',$hotel_ids];
        }
        if ($data['room_type_id']){
            $room_type['id'] = ['like','%'.$data['room_type_id'].'%'];
            $room_type_id = Db::name('hotel_room_type')->where($room_type)->column('id');
            $map['room_type_id'] = ['in',$room_type_id];
        }
        if ($data['remark']){
            $map['remark'] = ["like", "%{$data['remark']}%"];
        }
        $start_time = '';
        if ($data['check_in_date_start']){
            $start_time = "{$data['check_in_date_start']} 0:0:0"; //开始时间
            $end_time = "{$data['check_in_date_start']} 23:59:59"; // 结束时间
            $map['check_in_date'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }

        if ($data['check_in_date_end']){
            if(!$data['check_in_date_start']){
                $start_time = "{$data['check_in_date_end']} 0:0:0"; //开始时间
            }
            $end_time = "{$data['check_in_date_end']} 23:59:59"; // 结束时间
            $map['check_in_date'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }

        // 根据id查找
        $listRows = $this->request->param('numPerPage') ?20: Config::get("paginate.list_rows");
        $list = Db::name('driver_hotel_expense')
            ->where($map)
            ->order('id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];

        $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
        $count = $list->total();
        $this->view->assign("count", $count);
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('list', $listData);
        $this->view->assign('searchCondition',$data);
        $this->view->assign('hotel_room_type',$hotel_room_type);
        if($request->isAjax()){
            $this->view->assign("is_ajax", '1');
             return $this->view->fetch('driver_he_ajaxpage');
        }else{
            return $this->view->fetch('');
        }

    }

    /**
     * 司陪房费用添加
     */
    public function driver_he_add(Request $request)
    {
        $data = input();

        if($request->isAjax()){
            if($data['type'] == 'edit'){//编辑
                if($data['more'] && $data['more'] == 1) {//批量编辑
                    $dhe_ids = [];
                    $check_in_date = [];
                    $hName = [];
                    $hType = [];
                    $days = [];
                    $unit_price = [];
                    foreach ($data as $ck => $cv) {

                        $temp_ids = substr($ck, 0, 7);
                        $temp_check_in_date = substr($ck, 0, 14);
                        $temp_hName = substr($ck, 0, 6);
                        $temp_hType = substr($ck, 0, 6);
                        $temp_days = substr($ck, 0, 5);
                        $temp_unit_price = substr($ck, 0, 11);

                        if ($temp_ids == 'dhe_id_') {
                            $dhe_ids[] = $cv;
                        }
                        if ($temp_check_in_date == 'check_in_date_') {
                            if (empty($cv)) {
                                return ajax_return_adv_error('入住日期不能为空');
                            } else {
                                $check_in_date[] = $cv;
                            }
                        }
                        if ($temp_hName == 'hName_') {
                            if (empty($cv)) {
                                return ajax_return_adv_error('酒店名称不能为空');
                            } else {
                                $hName[] = $cv;
                            }
                        }
                        if ($temp_hType == 'hType_') {
                            if (empty($cv)) {
                                return ajax_return_adv_error('酒店房型不能为空');
                            } else {
                                $hType[] = $cv;
                            }
                        }
                        if ($temp_days == 'days_') {
                            if (empty($cv)) {
                                return ajax_return_adv_error('入住天数不能为空');
                            } else {
                                if (is_numeric($cv)) {
                                    $days[] = $cv;
                                } else {
                                    return ajax_return_error('入住天数格式输入有误');
                                }
                            }
                        }
                        if ($temp_unit_price == 'unit_price_') {
                            if (empty($cv)) {
                                return ajax_return_adv_error('房型费用不能为空');
                            } else {
                                if (is_numeric($cv)) {
                                    $unit_price[] = $cv;
                                } else {
                                    return ajax_return_error('房型费用格式输入有误');
                                }
                            }
                        }
                    }

                    $update_res = [];
                    $add_res = [];
                    if (count($dhe_ids) > 0) {
                        $dhr_info = Db::name('driver_hotel_expense')->where('id', $dhe_ids[0])->find();
                        foreach ($dhe_ids as $dk => $dv) {
                            if (!empty($dv)) {//可编辑数据
                                $update_data = [
                                    'check_in_date' => strtotime($check_in_date[$dk]),
                                    'status' => 2,
                                    'hotel_name' => $hName[$dk],
                                    'room_type_name' => $hType[$dk],
                                    'days' => $days[$dk],
                                    'unit_price' => $unit_price[$dk],
                                    'total_price' => $unit_price[$dk] * $days[$dk],
                                    'remark' => $data['remark'],
                                ];

                                $res = Db::name('driver_hotel_expense')->strict(false)->where('id', $dv)->update($update_data);
                                if ($res) {
                                    $update_res[] = $res;
                                }
                            } else {//新增数据

                                $insert_data = [
                                    'total_price' => $unit_price[$dk] * $days[$dk],
                                    'status' => 2,
                                    'create_time' => time(),
                                    'group_id' => $dhr_info['group_id'],
                                    'check_in_date' => strtotime($check_in_date[$dk]),
                                    'driver_user_id' => $dhr_info['driver_user_id'],
                                    'days' => $days[$dk],
                                    'unit_price' => $unit_price[$dk],
                                    'remark' => $data['remark'],
                                    'hotel_name' => $hName[$dk],
                                    'room_type_name' => $hType[$dk],
                                ];

                                $res = Db::name('driver_hotel_expense')->strict(false)->insert($insert_data);
                                if ($res) {
                                    $add_res[] = $res;
                                }
                            }
                        }
                        if (count($add_res) > 0 || count($update_res) > 0) {
                            return ajax_return_adv('编辑成功');
                        }else{
                            return ajax_return_adv_error('编辑失败');
                        }
                    } else {
                        return ajax_return_adv_error('无酒店记录可进行操作');
                    }
                } else{ //单个编辑

                    $rule = [
                        'id' => 'require|number',
                        'check_in_date' => 'require',
//                    'hotel_id'   => 'require',
//                    'room_type_id'   => 'require',
                        'hotel_name' => 'require',
                        'room_type_name' => 'require',
                        'days' => 'require|number',
                        'unit_price' => 'require|number',
                    ];
                    $msg = [
                        'id.require' => '参数错误',
                        'id.number' => '参数格式错误',
                        'check_in_date.require' => '请填写入住日期',
                        'hotel_name.require' => '请填写酒店名称',
                        'room_type_name.require' => '请填写酒店房型',
//                    'hotel_id.require' => '请选择酒店',
//                    'room_type_id.require' => '请选择酒店房型',
                        'days.require' => '请填写入住天数',
                        'days.number' => '入住天数格式填写错误，请填写数字',
                        'unit_price.require' => '请填写房型费用',
                        'unit_price.number' => '房型费用格式填写错误，请填写数字',
                    ];

                    $validate = new Validate($rule, $msg);
                    $result = $validate->check($data);
                    if (!$result) {
                        return ajax_return_adv_error($validate->getError());
                    }

                    $info = Db::name('driver_hotel_expense')->where('id', $data['id'])->find();

                    if ($info['status'] == 2 || $info['status'] == 0) {
                        $data['total_price'] = $data['unit_price'] * $data['days'];
                        $data['check_in_date'] = strtotime($data['check_in_date']);
                        $data['status'] = 2;
                        $res = Db::name('driver_hotel_expense')->strict(false)->where('id', $data['id'])->update($data);
                        if ($res) {
                            return ajax_return_adv('修改成功！');
                        } else {
                            return ajax_return_adv_error('修改失败！');
                        }
                    } else {
                        return ajax_return_adv_error('该记录当前状态不可修改！');
                    }
                }
            }else{//添加

                $check_in_date = [];
                $hName = [];
                $hType = [];
                $days = [];
                $unit_price = [];
                foreach ($data as $ck => $cv){
                    $temp_check_in_date = substr($ck,0,14);
                    $temp_hName = substr($ck,0,6);
                    $temp_hType = substr($ck,0,6);
                    $temp_days = substr($ck,0,5);
                    $temp_unit_price = substr($ck,0,11);

                    if($temp_check_in_date == 'check_in_date_'){
                        if(empty($cv)){
                            return ajax_return_adv_error('入住日期不能为空');
                        }else{
                            $check_in_date[] = $cv;
                        }
                    }
                    if($temp_hName == 'hName_'){
                        if(empty($cv)){
                            return ajax_return_adv_error('酒店名称不能为空');
                        }else{
                            $hName[] = $cv;
                        }
                    }
                    if($temp_hType == 'hType_'){
                        if(empty($cv)){
                            return ajax_return_adv_error('酒店房型不能为空');
                        }else{
                            $hType[] = $cv;
                        }
                    }
                    if($temp_days == 'days_'){
                        if(empty($cv)){
                            return ajax_return_adv_error('入住天数不能为空');
                        }else{
                            if(is_numeric($cv)){
                                $days[] = $cv;
                            }else{
                                return ajax_return_error('入住天数格式输入有误');
                            }
                        }
                    }
                    if($temp_unit_price == 'unit_price_'){
                        if(empty($cv)){
                            return ajax_return_adv_error('房型费用不能为空');
                        }else{
                            if(is_numeric($cv)){
                                $unit_price[] = $cv;
                            }else{
                                return ajax_return_error('房型费用格式输入有误');
                            }
                        }
                    }
                }

                $rule = [
                    'group_id'  => 'require|number',
//                    'check_in_date'   => 'require',
//                    'hotel_id'   => 'require',
//                    'room_type_id'   => 'require',
//                    'days'   => 'require|number',
//                    'unit_price'   => 'require|number',
                ];
                $msg = [
                    'group_id.require' => '参数错误',
                    'group_id.number' => '参数格式错误',
//                    'check_in_date.require' => '请填写入住日期',
//                    'hotel_id.require' => '请选择酒店',
//                    'room_type_id.require' => '请选择酒店房型',
//                    'days.require' => '请填写入住天数',
//                    'days.number' => '入住天数格式填写错误，请填写数字',
//                    'unit_price.require' => '请填写房型费用',
//                    'unit_price.number' => '房型费用格式填写错误，请填写数字',
                ];
                $validate = new Validate($rule,$msg);
                $result   = $validate->check($data);
                if(!$result){
                    return ajax_return_adv_error($validate->getError());
                }

                $is_apply_driver_hotel = Db::name('dispatch_traveler_group')->where('id',$data['group_id'])->value('is_apply_driver_hotel');

                if($is_apply_driver_hotel == 1){
                    return ajax_return_adv_error('该派车单已申请过司陪房');
                }

                Db::startTrans();
                try{
                    if(count($check_in_date) > 0){
                        $res = [];
                        $driver_user_id = Db::name('dispatch_traveler_group')->where('id',$data['group_id'])->value('driver_user_id');
                        if(!$driver_user_id){
                            return ajax_return_adv_error('该派车单未分配司导');
                        }
                        foreach ($check_in_date as $k => $v){
                            $insert_data = [
                              'total_price' => $unit_price[$k] * $days[$k],
                              'status' => 2,
                              'create_time' => time(),
                              'group_id' => $data['group_id'],
                              'check_in_date' => strtotime($v),
                              'driver_user_id' => $driver_user_id,
                              'days' => $days[$k],
                              'unit_price' => $unit_price[$k],
                              'remark' => $data['remark'],
                              'hotel_name' => $hName[$k],
                              'room_type_name' => $hType[$k],
                            ];

                            $res[] = Db::name('driver_hotel_expense')->strict(false)->insert($insert_data);
                        }

                        if(count($res) == count($check_in_date)){
                            $group_res = Db::name('dispatch_traveler_group')->where('id',$data['group_id'])->update(array('is_apply_driver_hotel'=>1));
                            if($group_res){
                                Db::commit();
                                return ajax_return_adv('申请成功');
                            }else{
                                Db::rollback();
                                return ajax_return_adv_error('申请失败');
                            }
                        }else {
                            Db::rollback();
                            return ajax_return_adv_error('申请失败');
                        }
                    }else{
                        return ajax_return_adv_error('请填写酒店记录');
                    }
                }catch (\Exception $e){
                    return ajax_return_adv_error($e->getMessage());
                }
            }
        }else{
            if($data['type'] == 'edit'){
                if(!$data['id']){
                    return ajax_return_adv_error('缺少参数id');
                }
                $info = Db::name('driver_hotel_expense')->where('group_id',$data['id'])->select();
                if(count($info) > 0){
                    $group_info = Db::name('dispatch_traveler_group')->where('id',$info[0]['group_id'])->find();
                    $group_id = $info[0]['group_id'];
                    $route_title = Db::name('route')->where('id',$group_info['route_id'])->value('title');
                    $driver_user_name = Db::name('admin_user')->where('id',$group_info['driver_user_id'])->value('realname');
                }else{
                    return ajax_return_adv_error('不存在相关信息');
                }

                $this->view->assign('group_id',$group_id);
                $this->view->assign('route_title',$route_title);
                $this->view->assign('driver_user_name',$driver_user_name);
                $this->view->assign('list',$info);
                $this->view->assign('count',count($info));
                $this->view->assign('type','edit');
                return $this->view->fetch('');
            }else{
                $map['dispatch_group_status'] = array('in',['achieve','proceed','receiving']);
                $map['isdelete'] = 0;
                $map['is_apply_driver_hotel'] = 0;
                $group = Db::name('dispatch_traveler_group')->where($map)->order('create_time desc')->field('id,driver_user_id,dispatch_group_status,route_id,isdelete')->select();
                foreach ($group as $k => $v){
                    $group[$k]['driver_user_name'] =  Db::name('admin_user')->where('id',$v['driver_user_id'])->value('realname');
                    $group[$k]['route_title'] =  Db::name('route')->where('id',$v['route_id'])->value('title');
                }
                $hotel = Db::name('hotel')->where('isdelete',0)->select();
                $this->view->assign('hotel',$hotel);
                $this->view->assign('group',$group);
                $this->view->assign('type','add');
                return $this->view->fetch('');
            }

        }
    }

    /**
     * 根据酒店ID获取酒店房型
     */
    public function get_hotel_room_type()
    {
        $data = input();
        if(!$data['id']){
            return ajax_return_error('请选择酒店');
        }

        $hotel_room_type = Db::name('room_hotel_number')->where('hotel_id',$data['id'])->where('isdelete',0)->select();

        if(count($hotel_room_type) > 0){
            foreach ($hotel_room_type as $k => $v){
                $hotel_room_type[$k]['room_name'] = Db::name('hotel_room_type')->where('id',$v['room_type_id'])->value('room_name');
            }
        }

        return json($hotel_room_type);
    }

    /**
     * 校验整合酒店结算申请单数据
     */
    public function hotel_settlement_pdf(){
        $data = input();
//        return ajax_return_adv_error('123','','','','','',$data);
        if(!$data['ck']){
            return ajax_return_adv_error('参数有误');
        }
        if(count($data['ck'])>0){
            $hotel_ck_hotel = [];
            $hotel_ck_account = [];
            $hotel_ck_account_name = [];
            $hotel_ck_account_bank = [];
            $hotel_accommodation = [];
            $min_check_in_date = 0;
            $max_end_date = 0;
            $total_price = 0;
            $balance_payment = 0;
            foreach ($data['ck'] as $k => $v){
                $hotel_accommodation[$v] = Db::name('hotel_accommodation')->where('id',$v)->field('id,hotel_id,account,account_name,account_bank,subscription,check_in_date,end_date,total_price,is_apply_settlement,is_reject,is_settlement,isdelete')->find();
                //判断信息是否完整
                if(empty($hotel_accommodation[$v]['hotel_id']) || empty($hotel_accommodation[$v]['total_price'])){
                    return ajax_return_adv_error('所选结算信息酒店信息缺失');
                }
                if(empty($hotel_accommodation[$v]['account']) || empty($hotel_accommodation[$v]['account_name']) || empty($hotel_accommodation[$v]['account_bank'])){
                    return ajax_return_adv_error('所选结算信息酒店账号信息缺失,请先进行完善');
                }
                if(empty($hotel_accommodation[$v]['check_in_date']) || empty($hotel_accommodation[$v]['end_date'])){
                    return ajax_return_adv_error('所选结算信息出发或结束日期信息不完整');
                }

                $balance_payment_temp = $hotel_accommodation[$v]['total_price'] - $hotel_accommodation[$v]['subscription'];
                //计算尾款总价
                $balance_payment = $balance_payment_temp + $balance_payment;

                //计算结算总价
                $total_price = $hotel_accommodation[$v]['total_price'] + $total_price;

                //取出结算周期
                if($min_check_in_date == 0){
                    $min_check_in_date = $hotel_accommodation[$v]['check_in_date'];
                }
                if($max_end_date == 0){
                    $max_end_date = $hotel_accommodation[$v]['end_date'];
                }
                if(!empty($hotel_accommodation[$v]['check_in_date']) && $min_check_in_date > $hotel_accommodation[$v]['check_in_date']){
                    $min_check_in_date = $hotel_accommodation[$v]['check_in_date'];
                }
                if(!empty($hotel_accommodation[$v]['end_date']) && $max_end_date < $hotel_accommodation[$v]['end_date']){
                    $max_end_date = $hotel_accommodation[$v]['end_date'];
                }

                $hotel_ck_hotel[$hotel_accommodation[$v]['hotel_id']] = true;
                $hotel_ck_account[$hotel_accommodation[$v]['account']] = true;
                $hotel_ck_account_name[$hotel_accommodation[$v]['account_name']] = true;
                $hotel_ck_account_bank[$hotel_accommodation[$v]['account_bank']] = true;
            }
            //判断结算的酒店信息是否一致
            if(count($hotel_ck_hotel)>1){
                return ajax_return_adv_error('所选结算信息酒店不一致');
            }
            if(count($hotel_ck_account)>1 || count($hotel_ck_account_name)>1 || count($hotel_ck_account_bank)>1){
                return ajax_return_adv_error('所选结算信息酒店账号信息不一致');
            }

            $hotel_id = array_keys($hotel_ck_hotel)[0];
            $hotel_name = Db::name('hotel')->where('id',$hotel_id)->value('hotel_name');
            $account = array_keys($hotel_ck_account)[0];
            $account_name = array_keys($hotel_ck_account_name)[0];
            $account_bank = array_keys($hotel_ck_account_bank)[0];

            $check_data['hotel_name'] = $hotel_name;
            $check_data['account_name'] = $account_name;
            $check_data['account'] = $account;
            $check_data['account_bank'] = $account_bank;
            $check_data['min_check_in_date'] = $min_check_in_date;
            $check_data['max_end_date'] = $max_end_date;
            $check_data['total_price'] = $balance_payment;

            //校验数据
            $rule = [
                'hotel_name'=>'require',
                'account_name'=>'require',
                'account'=>'require',
                'account_bank'=>'require',
                'min_check_in_date'=>'require',
                'max_end_date'=>'require',
                'total_price'=>'require',
            ];
            $message = [
                'id.require' => '酒店名称不能为空',
                'account_name.require' => '账号名称不能为空',
                'account.require' => '账号不能为空',
                'account_bank.require' => '账号开户行不能为空',
                'min_check_in_date.require' => '出发日期不能为空',
                'max_end_date.require' => '结束日期不能为空',
                'total_price.require' => '结算金额不能为空',
            ];
            $validate = new Validate($rule,$message);
            $result = $validate->check($check_data);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            return ajax_return_adv('正在导出中,请稍后','','','','',$check_data);
        }else{
            return ajax_return_adv_error('请先勾选');
        }
    }

    //酒店结算申请单pdf导出
    public function export_hotel_settlement_pdf(){
        $data = input();
        if (UID === 1) {
            $role = '超级管理员';
        } else {
            $role = Db::name('admin_role_user')
                ->alias('aru')
                ->join('tp_admin_role ar','ar.id=aru.role_id','left')
                ->where('aru.user_id',UID)
                ->value('ar.name');
        }
        $hotel_name = $data['hotel_name'];
        $account_name = $data['account_name'];
        $account = $data['account'];
        $account_bank = $data['account_bank'];
        $min_check_in_date = $data['min_check_in_date'];
        $max_end_date = $data['max_end_date'];
        $date = date('Y/m/d',$min_check_in_date).'-'.date('Y/m/d',$max_end_date);
        $total_price = $data['total_price'];
        ob_end_clean();
        $html = '
                <style>
                    .text-c{
                        text-align: center
                    }
                     .table{
                        border: 1px solid #ddd;
                     }
                     .table tr{
                        text-align: center;
                        display: table-row;
                        vertical-align: inherit;
                        border-color: inherit;
                     }
                      .table tr td{
                        border-left: 1px solid #ddd;
                        border-bottom: 1px solid #ddd;
                     }
                </style>
                <div style="text-align: center"><h1>酒店结算申请单</h1></div>
                <table class="table" cellspacing="0" cellpadding="6">
                    <tr>
                        <td colspan="1">结算酒店</td>
                        <td colspan="7">'.$hotel_name.'</td>
                    </tr>
                     <tr>
                        <td colspan="1">账户名称</td>
                        <td colspan="1">'.$account_name.'</td>
                        <td colspan="1">账号</td>
                        <td colspan="3">'.$account.'</td>
                        <td colspan="1">开户行</td>
                        <td colspan="1">'.$account_bank.'</td>
                    </tr>
                     <tr>
                        <td colspan="1">结算周期</td>
                        <td colspan="3">'.$date.'</td>
                        <td colspan="1">结算金额</td>
                        <td colspan="3">'.$total_price.'</td>
                    </tr>
                     <tr>
                        <td colspan="1">操作人</td>
                        <td colspan="3">'.$role.'</td>
                        <td colspan="1">申请日期</td>
                        <td colspan="3"></td>
                    </tr>
                     <tr>
                        <td colspan="1">主管复核</td>
                        <td colspan="3"></td>
                        <td colspan="1">财务核签</td>
                        <td colspan="3"></td>
                    </tr>
                </table>
                ';
         $title = $hotel_name.'结算申请单';
         $this->pdf($html,$title);
    }

    /**
     * 导出pdf接口
     * html:输出内容
     * title:标题
     * author:作者
     */
    function pdf($html,$title='',$author=''){

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // 设置打印模式,设置文档信息
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor($author);
        $pdf->SetTitle($title);
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, PHP, example, test, guide');

        // 是否显示页眉和是否显示页脚
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(true);

        // 设置页眉和页脚信息内容
        $pdf->SetHeaderData('logo.jpg', 40, 'Helloweba.com', '小白测试', array(0,64,255), array(0,64,128));
        $pdf->setFooterData(array(0,64,0), array(0,64,128));

        // 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('dejavusans', '', '12'));
        $pdf->setFooterFont(Array('dejavusans', '', '10'));

        // 设置间距
        $pdf->SetHeaderMargin('5');
        $pdf->SetFooterMargin('10');

        // 设置左、上、右的间距
        $pdf->SetMargins('10', '10', '10');

        // 设置是否自动分页  距离底部多少距离时分页
        $pdf->SetAutoPageBreak(TRUE, '15');

        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');

        // 设置行高
        $pdf->setCellHeightRatio(1);

        // 设置图像比例因子
        $pdf->setImageScale(1.25);

        //设置默认字体子集模式
        $pdf->setFontSubsetting(true);

        // 设置字体
        $pdf->SetFont('stsongstdlight', '', 12, '', true);
        $pdf->AddPage();
        $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

        //PDF输出   I：在浏览器中打开，D：下载，F：在服务器生成pdf ，S：只返回pdf的字符串
        $pdf->Output(($title).'.pdf', 'I');
    }
}
